package com.jf.template.stat.ast;

import java.io.Writer;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.jf.template.Env;
import com.jf.template.expr.ast.ExprList;
import com.jf.template.stat.Scope;
import com.wbcs.config.component.application.report.ReportBean;
import com.wbcs.system.ReportRequest;
import com.wbcs.system.WbcsResponse;
import com.wbcs.system.assistant.ComponentAssistant;
import com.wbcs.util.Consts;
import com.wbcs.util.Consts_Private;

public class Button extends Stat{

	private ExprList exprList;
	private HttpServletRequest request;
	private HttpServletResponse response;
	
	public Button(ExprList exprList, HttpServletRequest request, HttpServletResponse response){
		this.exprList = exprList;
		this.request = request;
		this.response = response;
	}
	
	public void exec(Env env, Scope scope, Writer writer) {
		ReportRequest rrequest;
		WbcsResponse wresponse;
		Object value = exprList.eval(scope);
		if (value != null && value.toString().split("\\.").length == 3) {
			String paramArr[] = value.toString().split("\\.");
			if(request.getAttribute(Consts_Private.REPORT_TEMPLATE) == null){
	            rrequest=new ReportRequest(request,Consts.DISPLAY_ON_PAGE);
				wresponse=new WbcsResponse(response);
				rrequest.setWResponse(wresponse);
	            wresponse.setRRequest(rrequest);
	            request.setAttribute(Consts_Private.REPORT_TEMPLATE, rrequest);
				try{
					rrequest.init(paramArr[0]);
				}catch(Exception e){
					e.printStackTrace();
				}finally{
					rrequest.destroy(true);//占用资源释放
				}
			}else{
				rrequest = (ReportRequest) request.getAttribute(Consts_Private.REPORT_TEMPLATE);
				wresponse = rrequest.getWResponse();
			}
            for(ReportBean rBean : rrequest.getLstAllReportBeans()){
            	if(rBean.getId().equals(paramArr[1])){
            		String buttonstr=ComponentAssistant.getInstance().showButton(rBean,rBean.getButtonsBean().getButtonByName(paramArr[2]),rrequest,null);
            		write(writer, buttonstr);
            		break;
            	}
            }
		}
	}

	public void exec(Env env, Scope scope, Writer writer, HttpServletRequest request, HttpServletResponse response) {
		this.request = request;
		this.response = response;
		exec(env,scope,writer);
	}

}
